#include "buffer.h"
#include <errno.h>
#include <sys/uio.h>
#include "socketops.h"

const char Buffer::kCRLF[] = "\r\n";
const size_t Buffer::kPrepend;
const size_t Buffer::kInitialSize;

ssize_t Buffer::ReadFd(int fd, int* saved_errno)
{
	char extra_buf[65536];
	struct iovec vec[2];
	const size_t writable = GetWritableSize();
	vec[0].iov_base = GetBegin() + write_index_;
	vec[0].iov_len = writable;
	vec[1].iov_base = extra_buf;
	vec[1].iov_len = sizeof(extra_buf);

	const int iovcnt = (writable < sizeof(extra_buf)) ? 2 : 1;
	const ssize_t n = readv(fd, vec, iovcnt);
	if (n < 0)
	{
		*saved_errno = errno;
	}
	else if ((size_t)n <= writable)
	{
		write_index_ += n;
	}
	else
	{
		write_index_ = buffer_.size();
		Append(extra_buf, n - writable);
	}
	return n;
}